% 4.1
F = [0.1 0.18 0.62 0.70];
A = [0 1 0];
% 10^(0.2/20)/10^(60/20) = 0.001
DEV = [0.001 1 0.001];
[N,Wn,BTA,FILTYPE] = kaiserord(F,A,DEV);
B = fir1(N-6, Wn, FILTYPE, kaiser( N+1-6,BTA ),'noscale'); % N-6=85;
figure(1);
freqz(B); % frequency response
figure(2);
impz(B,1); % impuls response

% 4.2
[n,fo,mo,w] = firpmord(F,A,DEV);
b = firpm(n+7,fo,mo,w); % n+7=32;
figure(3);
freqz(b);
figure(4);
impz(b,1); % impuls response

% 4.4
bits=16;% [16 12 10]
figure(5);
impz(bitround(b,bits),1); % impuls response
figure(6);
freqz(bitround(b,bits)); % frequency response

% 4.5
order=20; n=(2*order)+1; step=2*pi/(n-1);
omts = -pi:step:pi;
Hi = (omts./2)./(sin(omts./2)); % the desired frequency response H inverse
Hi(order+1)=1; % to get rid of the NaN at the zero-division.
% figure(1);    plot(omts,Hi);
idft = ifft(Hi);
% figure(2);  plot(omts,abs(idft));
% figure(3);  freqz(idft);
% figure(4);  impz(idft,1);
computedfr=freqz(idft,1,n);
difference = abs(computedfr')-abs(Hi);
figure; plot(abs(computedfr));
figure; plot(abs(Hi));
figure; plot(difference);

% 4.6
% specifications
Wp = [0.18 0.62]; Ws = [0.1 0.7];
Rp = 0.2; Rs = 60;

% Butterworth filter
[n,Wn] = buttord(Wp,Ws,Rp,Rs); % n=22
[b,a] = butter(n,Wn);
figure(7);
freqz(b,a);
buttern=n;
% Chebyshev (type 1) filter
[n,Wn] = cheb1ord(Wp,Ws,Rp,Rs); % n=10
[b,a] = cheby1(n,Rp,Wn);
figure(8);
freqz(b,a);
chebyn=n;
% Cauer (elliptic) filter
[n,Wn] = ellipord(Wp,Ws,Rp,Rs); % n=7
[b,a] = ellip(n,Rp,Rs,Wn); % transfer function sum(b(i)/1+a(i))
figure(9);
freqz(b,a); % plots frequency response and phase response
phase = phasez(b,a); % calculates phase
cauern=n;
% 4.7
figure(10);
impz(b,a); % impulse response
figure(11);
stepz(b,a); % step response
figure(12);
grpdelay(b,a); % matlab group delay function
[z,p,k] = ellip(n,Rp,Rs,Wn); % poles and zeros, k is gain
% z = roots(b);
% p = roots(a);
figure(13); grid ON;
polar(atan(imag(z)./real(z)) , abs(z), 'o'); % tan(theta) = overstaand/aanliggend
hold;
polar(atan(imag(p)./real(p)) , abs(p), 'x'); % theta = atan(imaginair/reeel)
hold;

% 4.8
br=bitround(b,12);
ar=bitround(a,12);
figure(14);
freqz(br,ar);
zr = roots(b);
pr = roots(a);
figure(15);grid ON;
polar(atan(imag(zr)./real(zr)) , abs(zr), 'o'); % tan(theta) = overstaand/aanliggend
hold;
polar(atan(imag(pr)./real(pr)) , abs(pr), 'x'); % theta = atan(imaginair/reeel)
hold;